package com.category.douyijia.interceptors;

import com.category.douyijia.BaseInterceptors;
import com.category.douyijia.model.User;
import com.category.douyijia.services.LoginService;
import com.jfinal.aop.Inject;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;

public class LoginInterceptor implements BaseInterceptors {
	/**
	 * 引入登录业务对象设置为IOC
	 */
	@Inject
	LoginService loginService;
	
	@Override
	public void intercept(Invocation inv) {
		// TODO Auto-generated method stub
		Controller controller = inv.getController();
		User user = controller.getAttr(LoginService.LOGIN_USER);
		if (user != null) {
			inv.invoke();
			return ;
		}
		// ajax 请求不能使用 forwardAction(...)、redirect(...)，否则登录界面将被插入到页面右侧
		if (isAjaxRequest(controller)) {
			controller.renderJson(Ret.fail("msg", "当前账户已退出登录，请刷新页面并重新登录"));
		} else {
			controller.forwardAction("/login");
		}
	}

	/**
	 * 判断是否为 ajax 请求
	 */
	boolean isAjaxRequest(Controller c) {
		return "XMLHttpRequest".equalsIgnoreCase(c.getRequest().getHeader("X-Requested-With"));
	}
}
